#include<iostream>
#include <sys/socket.h>
#include <unistd.h>
#include <string>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>

class udpclient
{
private:
    int _sockfd;
    std::string _ip;
    int _port;
public:
    udpclient(std::string ip, int port)
        :_sockfd(-1)
        ,_ip(ip)
        ,_port(port)
    {}

    bool InitServer()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        { 
            std::cerr << "create socket fail!" << std::endl;
            return false;
        }

        std::cout << "create socket success!" << std::endl;
        std::cout << _sockfd << std::endl;

        return true;
    }

    void start()
    {
        std::string msg;
		struct sockaddr_in peer;
		memset(&peer, '\0', sizeof(peer));
		peer.sin_family = AF_INET;
		peer.sin_port = htons(_port);
		peer.sin_addr.s_addr = inet_addr(_ip.c_str());

		for (;;)
        {
			std::cout << "Please Enter# ";
			getline(std::cin, msg);
			sendto(_sockfd, msg.c_str(), msg.size(), 0, (struct sockaddr*)&peer, sizeof(peer));

        #define SIZE 128
		        char buffer[SIZE];
                struct sockaddr_in temp;
                socklen_t len = sizeof(temp);
                ssize_t size = recvfrom(_sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&temp, &len);
                if(size > 0)
                {
                    buffer[size] = '\0';
                    std::cout << buffer << std::endl;
                }
		}
    }

    ~udpclient()
    {
        if(_sockfd >= 0)
        {
            close(_sockfd);
        }
    }
};

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        std::cerr << "Useage: " << "ip and port" << std::endl;
        return 1; 
    }

    std::string ip = argv[1];
    int port = atoi(argv[2]);
    udpclient* clt = new udpclient(ip, port);
    clt->InitServer();
    clt->start();
    return 0;
}